package com.dingreading.cloud.soms.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import com.dingreading.cloud.common.util.excel.ExcelHandler;
import com.dingreading.cloud.soms.dto.MemberFollowDto;
import com.dingreading.cloud.soms.dto.vo.FollowVO;
import com.dingreading.cloud.soms.entity.MemberFollow;
import com.dingreading.cloud.soms.entity.MemberFollowImg;
import com.dingreading.cloud.soms.entity.Members;
import com.dingreading.cloud.soms.service.MemberFollowImgService;
import com.dingreading.cloud.soms.service.MemberFollowService;
import com.dingreading.cloud.soms.service.MembersService;
import com.dingreading.cloud.soms.util.FollowUtil;
import com.dingreading.cloud.soms.util.redis.RedisService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/memberFollow")
@Api(tags = "门店-会员跟进管理")
public class FrontMemberFollowController {

    @Resource
    protected MembersService membersService;
    @Resource
    protected MemberFollowService memberFollowService;
    @Resource
    protected MemberFollowImgService memberFollowImgService;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "获取会员的根据记录")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid", required = false) String memberUid,
            @ApiParam(value = "会员姓名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "跟进类型") @RequestParam(value = "followUid", required = false) String followUid,
            @ApiParam(value = "跟进开始日期") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "跟进结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "来源 1.系统 2.员工") @RequestParam(value = "source", required = false) Integer source,
            @ApiParam(value = "跟进员工uid") @RequestParam(value = "followStaffUid", required = false) String followStaffUid
    ) {
        Page<MemberFollowDto> page = memberFollowService.pageList(
                pageUtil, storeUid, memberUid, followUid, beginDate, endDate, keyword, source, followStaffUid
        );

        List<MemberFollowDto> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> uidList = list.stream().map(MemberFollowDto::getUid).collect(Collectors.toList());
            List<MemberFollowImg> imgList = memberFollowImgService.listByFollowUidIn(uidList);
            if (CollectionUtils.isNotEmpty(imgList)) {
                Map<String, List<MemberFollowImg>> imgMap = imgList.stream().collect(Collectors.groupingBy(MemberFollowImg::getFollowUid));
                for (MemberFollowDto dto : list) {
                    List<MemberFollowImg> imgs = imgMap.get(dto.getUid());
                    if (CollectionUtils.isNotEmpty(imgs))
                        dto.setImgList(imgs);
                }
            }
        }

        PageBeanDto dto = new PageBeanDto();
        dto.setList(list);
        dto.setTotal(page.getTotalRow());
        return R.ok(dto);
    }

    @ApiOperation(value = "创建会员的跟进记录")
    @PostMapping(value = "/newMemberFollow", produces = "application/json; charset=UTF-8")
    public R<Object> newMemberFollow(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "跟进记录uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "跟进类型uid") @RequestParam(value = "followUid") String followUid,
            @ApiParam(value = "跟进类型名称") @RequestParam(value = "followType") String followType,
            @ApiParam(value = "跟进时间") @RequestParam(value = "followTime") String followTime,
            @ApiParam(value = "跟进内容") @RequestParam(value = "content") String content,
            @ApiParam(value = "跟进人uid") @RequestParam(value = "followStaffUid") String followStaffUid,
            @ApiParam(value = "跟进人姓名") @RequestParam(value = "followStaffName") String followStaffName,
            @ApiParam(value = "跟进图片集合[{id:0,imgUrl:''}]") @RequestParam(value = "imgJson", required = false) String imgJson
    ) throws Exception {
        if (StringUtils.isBlank(followUid))
            return R.fail("请选择跟进类型");
        if (StringUtils.isBlank(content))
            return R.fail("请输入跟进内容");
        if (StringUtils.isBlank(followStaffName))
            return R.fail("请去 店员管理模块 填写跟进人姓名");

        List<MemberFollowImg> imgList = new ArrayList<>();
        if (StringUtils.isNotBlank(imgJson)) {
            imgList = JSONObject.parseArray(imgJson, MemberFollowImg.class);
            if (CollectionUtils.isEmpty(imgList))
                return R.fail("跟进图片转换失败");
            if (imgList.size() > 10)
                return R.fail("跟进图片不能超过10张");
        }

        Members members = membersService.getByUid(storeUid, memberUid);
        if (null == members)
            return R.fail("获取会员信息失败");

        MemberFollow data = null;
        if (StringUtils.isNotBlank(uid)) {
            data = memberFollowService.getBean(uid);
            if (null == data)
                return R.fail("跟进记录不存在");
            if (!data.getSource().equals(2))
                return R.fail("只能编辑员工添加的跟进记录");
            if (TimeUtil.moreThanDay(data.getAddTime(), 30))
                return R.fail("添加已超过30天，不能操作");
        }

        Date fTime = DateUtil.parseDateFromStr(followTime);
        // 创建跟进记录
        data = FollowUtil.newFollowHand(
                data, corpUid, storeUid, storeName, staffUid, staffName,
                memberUid, members.getMemberName(), followUid, followType,
                content, null, fTime, followStaffUid, followStaffName
        );
        memberFollowService.saveOrUpdate(data);

        // 更新会员最进跟进信息
        if (StringUtils.isBlank(uid)) {
            membersService.updateLastFollowInfo(storeUid, memberUid, data.getUid(), fTime);
        }

        // 创建跟进图片
        dealImgList(imgList, data.getUid(), staffUid, staffName);
        return R.ok();
    }

    @ApiOperation(value = "删除员工添加的跟进记录")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "跟进记录uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid
    ) {
        MemberFollow data = memberFollowService.getBean(uid);
        if (null == data) return R.fail("跟进记录不存在");
        if (!data.getSource().equals(2)) return R.fail("只能删除员工添加的跟进记录");

        if (TimeUtil.moreThanDay(data.getAddTime(), 30))
            return R.fail("添加已超过30天，不能操作");

        long l = memberFollowService.dropBean(storeUid, memberUid, uid);
        if (l <= 0)
            return R.failDel();

        List<MemberFollowImg> imgList = memberFollowImgService.listByFollowUid(uid);
        if (CollectionUtils.isNotEmpty(imgList)) {
            // 删除跟进图片
            int i = memberFollowImgService.dropByFollowUid(uid);
            if (i > 0) {
                List<String> urls = imgList.stream().map(MemberFollowImg::getImgUrl).collect(Collectors.toList());
                deleteOssFiles(urls);
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "删除员工添加的跟进记录")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "跟进记录uid") @RequestParam(value = "uid") String uid
    ) {
        MemberFollowDto data = memberFollowService.getDto(uid);
        if (null == data)
            return R.fail("跟进记录不存在");
        if (!data.getSource().equals(2))
            return R.fail("不是员工添加的跟进记录，不能操作");

        List<MemberFollowImg> list = memberFollowImgService.listByFollowUid(uid);
        data.setImgList(list);

        return R.ok(data);
    }

    @ApiOperation(value = "批量分配跟进人")
    @PostMapping(value = "/allotFollowStaff", produces = "application/json; charset=UTF-8")
    public R<Object> allotFollowStaff(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "会员uid集合") @RequestParam(value = "memberUids") List<String> memberUids,
            @ApiParam(value = "跟进人uid") @RequestParam(value = "followStaffUid") String followStaffUid,
            @ApiParam(value = "跟进人姓名") @RequestParam(value = "followStaffName") String followStaffName
    ) {
        List<Members> members = membersService.getByUids(memberUids);
        if (CollectionUtils.isEmpty(members)) return R.fail("获取会员信息失败");

        boolean l = membersService.allotFollowStaff(storeUid, memberUids, followStaffUid, followStaffName);
        if (!l) return R.fail("分配跟进人失败");

        // 批量更新会员最后跟进时间
        Date followTime = DateUtil.getNowDatetime();
        //TODO 创建跟进记录
        List<MemberFollow> newList = new ArrayList<>();
        for (Members member : members) {
            MemberFollow data = FollowUtil.newFollow(corpUid, storeUid, storeName, staffUid, staffName,
                    member.getUid(), member.getMemberName(),
                    EnumType.Follow.ALLOT_STAFF.getType(), EnumType.Follow.ALLOT_STAFF.getName(),
                    staffName + " 将会员分配给了 " + followStaffName, null, followTime);
            newList.add(data);
            // 更新会员跟进信息
            membersService.updateLastFollowInfo(storeUid, member.getUid(), data.getUid(), followTime);
        }
        memberFollowService.saveOrUpdateBatch(newList);

        // 清空门店会员缓存
        redisService.setNullLike(RedisParam.STORE_MEMBERS + storeUid);
        return R.ok();
    }

    @ApiOperation(value = "取消跟进")
    @PostMapping(value = "/giveUp", produces = "application/json; charset=UTF-8")
    public R<Object> giveUp(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "放弃原因") @RequestParam(value = "remark", required = false) String remark
    ) {
        Members member = membersService.getByUid(storeUid, memberUid);
        if (null == member) return R.fail("获取会员信息失败");

        Date time = DateUtil.getNowDatetime();
        boolean l = membersService.giveUp(storeUid, memberUid, null);
        if (!l) return R.fail("放弃会员失败");

        //TODO 创建跟进记录
        String content = staffName + " 放弃跟进 " + member.getFullName();
        if (StringUtils.isNotBlank(remark))
            content = content + "，放弃原因：" + remark;
        MemberFollow follow = FollowUtil.newFollow(corpUid, storeUid, storeName,
                staffUid, staffName, member.getUid(), member.getMemberName(),
                EnumType.Follow.GIVE_UP.getType(), EnumType.Follow.GIVE_UP.getName(), content, null, time);
        memberFollowService.saveOrUpdate(follow);
        // 更新会员的最后跟进信息
        membersService.updateLastFollowInfo(storeUid, memberUid, follow.getUid(), time);

        // 清空门店会员缓存
        redisService.setNullLike(RedisParam.STORE_MEMBERS + storeUid);
        return R.ok();
    }

    @ApiOperation(value = "导出跟进记录")
    @PostMapping(value = "/exportList", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void exportList(
            HttpServletResponse response,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid", required = false) String memberUid,
            @ApiParam(value = "会员姓名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "跟进类型") @RequestParam(value = "followUid", required = false) String followUid,
            @ApiParam(value = "跟进开始日期") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "跟进结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "来源 1.系统 2.员工") @RequestParam(value = "source", required = false) Integer source,
            @ApiParam(value = "跟进员工uid") @RequestParam(value = "followStaffUid", required = false) String followStaffUid
    ) throws Exception {
        if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
            // 默认查当月
            Date monthMinDate = DateUtil.getMonthMinDate();
            Date monthMaxDate = DateUtil.getMonthMaxDate();
            beginDate = DateUtil.getDefaultTime2DateStr(monthMinDate);
            endDate = DateUtil.getDefaultTime2DateStr(monthMaxDate);
        }

        List<MemberFollow> list = memberFollowService.getList(storeUid, memberUid, followUid, beginDate, endDate, keyword,
                source, followStaffUid);

        List<FollowVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (MemberFollow follow : list) {
                FollowVO vo = new FollowVO();
                vo.setStoreName(follow.getStoreName());
                vo.setMemberName(follow.getMemberName());
                vo.setFollowType(follow.getFollowType());
                vo.setContent(follow.getContent());
                vo.setStaffName(follow.getFollowStaffName());
                if (follow.getFollowTime() != null)
                    vo.setFollowTime(DateUtil.getDefaultTimeStr(follow.getFollowTime()));
                if (follow.getAddTime() != null)
                    vo.setAddTime(DateUtil.getDefaultTimeStr(follow.getAddTime()));
                if (null != follow.getSource())
                    vo.setSource(follow.getSource().equals(1) ? "系统" : "员工");

                // 加入导出列表
                voList.add(vo);
            }
        }
        String name = "跟进记录" + beginDate + "-" + endDate;
        ExcelHandler.exportExcel(response, voList, FollowVO.class, name, "跟进记录", false);
    }

    /**
     * 创建或更新付款图片
     */
    private void dealImgList(List<MemberFollowImg> imgList, String followUid, String staffUid, String staffName) {
        if (CollectionUtils.isEmpty(imgList)) {
            // 删除订单的所有付款截图
            List<String> urlList = memberFollowImgService.urlListByFollowUid(followUid);
            int i = memberFollowImgService.dropByFollowUid(followUid);
            // 删除阿里云图片
            if (i > 0)
                deleteOssFiles(urlList);
        } else {
            List<MemberFollowImg> newImgList = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
            for (MemberFollowImg pic : imgList) {
                if (null == pic.getId() || pic.getId() <= 0) {
                    pic.setFollowUid(followUid);
                    pic.setAddStaffUid(staffUid);
                    pic.setAddStaffName(staffName);
                    newImgList.add(pic);
                } else {
                    ids.add(pic.getId());
                }
            }
            // 先删除不要的数据
            List<String> urlList = memberFollowImgService.urlListByFollowUidAndIdNot(followUid, ids);
            int i = memberFollowImgService.dropByFollowUidAndIdNot(followUid, ids);
            // 删除阿里云图片
            if (i > 0)
                deleteOssFiles(urlList);
            // 再保存新数据
            if (CollectionUtils.isNotEmpty(newImgList))
                memberFollowImgService.saveOrUpdateBatch(newImgList);
        }
    }

    /**
     * 删除阿里云上存储的文件
     */
    public static void deleteOssFiles(List<String> fileUrls) {
        // 生产环境且阿里云文件地址不为空，才能删除
        if (CollectionUtils.isNotEmpty(fileUrls)) {
            // 删除阿里云图片
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.initOss();
            ossClientUtil.deleteFiles(OSSClientUtil.publicBucket, fileUrls);
        }
    }

}